package com.team.mp.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.team.mp.api.bo.SysPermissionAddBo;
import com.team.mp.api.bo.SysPermissionBo;
import com.team.mp.mapper.dao.SysPermissionDao;
import com.team.mp.mapper.dao.SysRolePermissionDao;
import com.team.mp.mapper.entity.SysPermission;
import com.team.mp.mapper.entity.SysRolePermission;
import com.team.mp.api.service.intf.SysPermissionService;
import com.team.mp.api.util.AuthUtil;
import com.team.mp.api.util.MenuUtil;
import com.team.mp.vo.R;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 18.权限表(SysPermission)表服务实现类
 *
 * @author makejava
 * @since 2023-03-26 10:40:28
 */
@Service
public class SysPermissionServiceImpl implements SysPermissionService {

    @Resource
    private SysPermissionDao dao;
    @Resource
    private SysRolePermissionDao rolePermissionDao;


    @Override
    public R add(SysPermissionBo bo) {
        //1.验证
        if(bo!=null){
            SysPermission permission=new SysPermission();
            BeanUtils.copyProperties(bo,permission);
            if(dao.insert(permission)>0){
                return R.ok();
            }
        }
        return R.fail();
    }

    @Override
    public R queryAll() {
       //1.查询
        QueryWrapper<SysPermission> wrapper=new QueryWrapper<>();
        wrapper.orderByAsc("type");
        wrapper.orderByAsc("level");
        List<SysPermission> list=dao.selectList(wrapper);
        return R.ok(MenuUtil.ceateMenu(list));
    }

    @Override
    public R queryMenuByUid() {
        List<SysPermission> list=dao.selectMenuByUid(AuthUtil.getUid());
        return R.ok(MenuUtil.parseMenu(MenuUtil.ceateMenu(list)));
    }

    @Override
    public R queryPermByUid() {
        return R.ok(dao.selectPermByUid(AuthUtil.getUid()));
    }

    @Override
    public R updateByUid(SysPermissionAddBo bo) {
        //1.先删除原来的
        rolePermissionDao.deleteByRid(bo.getRid());
        //2.再新增本次的
        List<SysRolePermission> list=new ArrayList<>(bo.getPids().size());
        bo.getPids().forEach(pid->{
            list.add(new SysRolePermission(bo.getRid(),pid));
        });
        rolePermissionDao.insertBatch(list);
        return R.ok();
    }

}

